package com.ruoyi.pyo.wechat.config;

import com.ruoyi.pyo.wechat.cache.WeChatCacheTemplate;
import com.ruoyi.pyo.wechat.cache.WeChatCaffineCache;
import com.ruoyi.pyo.wechat.tools.WeChatTools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Configuration
@ConditionalOnProperty(name = "wechat.conf.enabled")
@EnableConfigurationProperties(WeChatProps.class)
@RequiredArgsConstructor
public class WeChatConfig {

    private final WeChatProps weChatProps;

    /**
     * 当不存在此 wxRestTemplate 使用此方法的bean注入
     *
     * @return RestTemplate
     */
    @Bean
    @ConditionalOnMissingBean(name = "weChatRestTemplate")
    public RestTemplate weChatRestTemplate() {
        //复杂构造函数的使用
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 设置超时
        requestFactory.setConnectTimeout(6000);
        requestFactory.setReadTimeout(6000);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }

    /**
     * 当不存在此 wxCacheTemplate 使用此方法的bean注入
     *
     * @return WeChatCacheTemplate
     */
    @Bean
    @ConditionalOnMissingBean(name = "weChatCacheTemplate")
    public WeChatCacheTemplate weChatCacheTemplate() {
        return new WeChatCaffineCache();
    }

    @Bean
    @ConditionalOnMissingBean(name = "weChatTools")
    public WeChatTools weChatTools() {
        return new WeChatTools(weChatRestTemplate(), weChatProps, weChatCacheTemplate());
    }

}
